package org.example.codeservce.util;

import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.domain.ExtendParams;
import com.alipay.api.domain.GoodsDetail;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.example.codeservce.config.AlipaySelfConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * author: Li Qing
 * date: 2024/5/15 16:01
 * description: 支付宝的支付工具类
 */
@Component
public class AlipayUtil
{
    @Resource
    private AlipaySelfConfig alipayConfig;

    private AlipayClient alipayClient;
    //创建日志打印
    private static final Logger log = LoggerFactory.getLogger(AlipayUtil.class);


    @PostConstruct
    public void init()
    {
        alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                                               alipayConfig.getAppId(), alipayConfig.getPrivateKey(),
                                               "json", "GBK",
                                               alipayConfig.getAlipayPublicKey(), "RSA2");
    }


    /**
     * 查询交易  的支付状态和金额
     *
     * @param outTradeNo 订单号
     * @return 实际支付金额
     */
    @SneakyThrows
    public String selectPayPrice(String outTradeNo)
    {
        // 构造请求参数以调用接口
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();

        // 设置订单支付时传入的商户订单号
        model.setOutTradeNo(outTradeNo);

        // 设置查询选项
        List<String> queryOptions = new ArrayList<String>();
        //交易结算金额
        queryOptions.add("trade_settle_info");
        model.setQueryOptions(queryOptions);

        request.setBizModel(model);
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        if (response.isSuccess())
        {
            //支付成功
            if (Objects.equals(response.getTradeStatus(), "TRADE_SUCCESS"))
            {
                //实际支付宝金额
                return response.getReceiptAmount();
            }
        }
        else
        {
            log.info("调用失败，出错原因：{}", JSONUtil.toJsonStr(response));
        }
        return null;
    }

    /**
     * 构建支付二维码
     *
     * @param orderTitle 商品标题
     * @param price      支付金额
     * @param showPayUrl 展示url
     * @param outTradeNo 订单号
     * @return 二维码地址
     */
    @SneakyThrows
    public String builderPay(String orderTitle, String price, String showPayUrl, String outTradeNo)
    {
        // 构造请求参数以调用接口
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();

        // 设置商户门店编号
        model.setStoreId("LQ");

        // 设置订单标题
        model.setSubject(orderTitle);

        // 设置商户操作员编号
        model.setOperatorId("yx_001");

        // 设置产品码
        model.setProductCode("FACE_TO_FACE_PAYMENT");

        // 设置订单附加信息
        model.setBody(orderTitle);

        // 设置订单包含的商品列表信息
        List<GoodsDetail> goodsDetail = new ArrayList<GoodsDetail>();
        GoodsDetail goodsDetail0 = new GoodsDetail();
        goodsDetail0.setGoodsName(orderTitle);
        goodsDetail0.setQuantity(1L);
        goodsDetail0.setPrice(price);
        goodsDetail0.setShowUrl(showPayUrl);
        goodsDetail.add(goodsDetail0);
        model.setGoodsDetail(goodsDetail);


        // 设置商户订单号
        model.setOutTradeNo(outTradeNo);

        // 设置订单总金额
        model.setTotalAmount(price);

        // 设置商户机具终端编号
        model.setTerminalId("NJ_T_002");

        request.setBizModel(model);
        AlipayTradePrecreateResponse response = alipayClient.execute(request);
        System.out.println(response.getBody());

        if (response.isSuccess())
        {
            return response.getQrCode();
        }
        else
        {
            log.info("调用失败，出错原因：{}", JSONUtil.toJsonStr(response));
        }
        return null;
    }
}
